package handler;

import enums.MessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import protocol.Header;
import protocol.NettyMessage;

/**
 * 服务的心跳应答
 */
public class HeartHeatRespHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    System.out.println("开启心跳");
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;
    //返回心跳应答消息
    if (message.getHeader() != null
        && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()){
      System.out.println("Receive client heart beat message : ---> "+message);
      NettyMessage heatBeat = buildHeatBeat();
      ctx.writeAndFlush(message);
    }else {
      ctx.fireChannelRead(msg);
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.close();
    cause.printStackTrace();
  }
  private NettyMessage buildHeatBeat(){
    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setType(MessageType.HEARTBEAT_RESP.value());
    message.setHeader(header);
    return message;
  }
}
